<?php

class Frame extends Model {
	
    function Frame()
    {
        parent::Model();
    }
	
	
	function getFrames($idCol)
	{
		$sql = "SELECT * FROM `SLIDES` WHERE ID IN (
			SELECT ID_SLIDE AS ID FROM `COLLECTIONS_SLIDES`
			WHERE ID_COL = ".$idCol."
		) ORDER BY ID";
		
		$query = $this->db->query($sql);
		
		return $query->result_array();
	}
	
	function getFrame($id)
	{
		$sql = "SELECT * FROM SLIDES WHERE ID=".$id;
        $query = $this->db->query($sql);
		
		return $query->row();
	}
	
	function getColId($id)
	{
		$sql = "SELECT ID_COL as ID FROM `COLLECTIONS_SLIDES` WHERE ID_SLIDE=".$id;
		$query = $this->db->query($sql);
		
		return $query->row();
	}
    
	
	function insert($idCol, $titre, $contenu)
	{
		$titre		= mysql_real_escape_string($titre);
		$contenu	= mysql_real_escape_string($contenu);
		$collection	= $idCol;
		
		$sql = "INSERT INTO SLIDES (ID, TITRE, CONTENU)
		        VALUES ('', '".$titre."', '".$contenu."')";
		$this->db->query($sql);
		
		$idFrame = mysql_insert_id();
		
		$sql = "SELECT MAX( ID ) as id FROM SLIDES";
		$query = $this->db->query($sql);
		$id = $query->row()->id;
		
		$this->insertRelation($collection, $id);
		
		return $idFrame;
		// creation de la miniature
		
	}
	
	function insertRelation($idCol, $idFrame)
	{
		$sql = "INSERT INTO COLLECTIONS_SLIDES VALUES ('".$idCol."','".$idFrame."')";
		$this->db->query($sql);
	}
	
	function update($id, $titre, $tex)
	{	
		$sql = "UPDATE SLIDES SET TITRE='".$titre."', CONTENU='".$tex."' WHERE ID=".$id;
		$query = $this->db->query($sql);
		
		// recreation de la miniature
	}
	
	function delete($idFrame, $idCol)
	{	
		// suppression de la frame correspondant a la collection
		$sql = "DELETE FROM COLLECTIONS_SLIDES WHERE ID_COL=".$idCol." AND ID_SLIDE=".$idFrame;
		$query = $this->db->query($sql);
		
		// compte le nombre d'occurence de cette frame dans toutes les collections
		$sql = "SELECT count(*) as nb FROM COLLECTIONS_SLIDES WHERE ID_SLIDE=".$idFrame;
		$query = $this->db->query($sql);
		
		$nb = $query->row()->nb;
		
		// si le nombre d'occurence est égale à 0 alors on supprime également la frame
		if ($nb==0)
		{
			$sql = "DELETE FROM SLIDES WHERE ID=".$idFrame;
			$query = $this->db->query($sql);
			
			// suppresion de la miniature
			$sql = "SELECT DIR FROM COLLECTIONS WHERE ID=".$idCol;
			$query = $this->db->query($sql);
			$dir = $query->row()->DIR;
			exec('rm '.$this->config->item('dirUpload').$dir.'/thumbs/'.$idFrame.'.gif');
		}
	}
	
	function getNbFrameOf($idCol)
	{
		$sql = "SELECT count(*) as nb FROM COLLECTIONS_SLIDES WHERE ID_COL=".$idCol;
		$query = $this->db->query($sql);
		
		return $query->row()->nb;
	}
	
	function getFirstPage($idCol)
	{
		$sql = "SELECT MIN(ID_SLIDE) as nb FROM COLLECTIONS_SLIDES WHERE ID_COL=".$idCol;
		$query = $this->db->query($sql);
		
		return $query->row()->nb;
	}

}
?>